<template>
	<view style="width: 1200rpx; height: 1200rpx; margin: 50rpx;">
		<map :show-location="true" 
		:latitude="latitude" :longitude="longitude" 
		:markers="markers" 
		class="maps"
		>
		</map>
	</view>
</template>

<script setup>
	import {
		onMounted,
		reactive,
		ref,
		watch,
		toRefs
	} from 'vue';
	const latitude = ref(43.62595);
	const longitude = ref(87.501952);
	const markers = reactive([{
		id: Date.now(),
		latitude: latitude.value,
		longitude: longitude.value,
		width: 20,
		height: 20,
		iconPath: '../../../static/Markers.png'
	}]);



	onMounted(() => {
		// console.log(markers,'········markers');
		const id = uni.getStorageSync('idss')
		uni.getLocation({
			type: 'wgs84',
			success: function(res) {
				console.log(res, 'resssssssssssssssss');
				// console.log('当前位置的经度：' + res.longitude);
				// console.log('当前位置的纬度：' + res.latitude);
			}
		})
		getSocket()
		// 设置一个心跳包
		const timer = setInterval(() => {
			uni.sendSocketMessage({
				data: JSON.stringify({
					mode: 'HEART_BEAT父方法'
				}),
			});
		}, 10000)
		uni.onSocketError((result) => {
			console.log(result, '服务器连接失败');
			reconnect(`ws://localhost:8088/ws?id=${id}`)
		})
		uni.onSocketClose(function(res) {
			console.log('WebSocket服务器已关闭！！！');
			reconnect(`ws://localhost:8088/ws?id=${id}`)
		});

		function reconnect(service) {
			// lockReconnect加锁，防止onclose、onerror两次重连
			timeConnect.value++;
			console.log("正在尝试第" + timeConnect.value + "次重连");
			uni.connectSocket({
				url: service
			});
		}
	})
	const getSocket = () => {
		const id = uni.getStorageSync('idss')
		uni.connectSocket({
			url: `ws://localhost:8088/ws?id=${id}`,
			success: (result) => {
				console.log(result, '连接成功');
			},
			fail: (error) => {
				console.log(error);
			}
		})
	}



	//接收服务器WebSocket返回数据API
	uni.onSocketMessage(function(res) {
		console.log('收到服务器内容333：', JSON.parse(res.data));
		const data = JSON.parse(res.data)
		// const {
		// 	mode,
		// 	latitude,
		// 	longitude
		// } = data
		// console.log(mode, latitude, longitude, '添加输出语句');
		if (data.mode === '') {
			console.log('服务器连接已断开，请重连！！！')
		}
		switch (data.mode) {
			case 'MESSAGE':
				console.log('测试消息数据')
				break
			case 'HEART_BEAT父方法':
				markers.push({
					id: Date.now(),
					latitude: data.latitude,
					longitude: data.longitude,
					width: 20,
					height: 20,
					iconPath: '../../../static/Markers.png'
				})
				console.log('父方法呀￥￥', markers, 888888)
				break
		}
	})
</script>

<style>
	.maps {
		width: 60%;
		height: 90%;
	}
</style>